<template>
  <a-modal
    :visible="visible"
    title="新增"
    cancelText="取消"
    okText="提交"
    width="80%"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="formState.state"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-row>
        <a-col :span="8">
          <a-form-item label="联系人姓名" name="contactsName">
            <a-input v-model:value="formState.state.contactsName" placeholder="请输入" maxlength="50"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="所属部门" name="contactsDepartment">
            <a-input v-model:value="formState.state.contactsDepartment" placeholder="请输入" maxlength="50" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="职位" name="contactsPosition">
            <a-input v-model:value="formState.state.contactsPosition" placeholder="请输入" maxlength="50" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="8">
          <a-form-item label="所属学校" name="schName">
            <a-input v-model:value="formState.state.schName" readonly placeholder="请选择">
              <template #addonAfter>
                <div class="primary-color cursor-pointer" @click="openDialog('schName')">选择</div>
              </template>
            </a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-item label="负责人" name="responsiblePerson">
            <a-input v-model:value="formState.state.responsiblePerson" placeholder="请选择">
              <template #addonAfter>
                <div class="primary-color cursor-pointer" @click="openDialog('responsiblePerson')">选择</div>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="电话" name="contactsPhone">
            <a-input v-model:value="formState.state.contactsPhone" placeholder="请输入" maxlength="11" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="邮箱" name="contactsEmail">
            <a-input v-model:value="formState.state.contactsEmail" placeholder="请输入" maxlength="50" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="性别" name="contactsSex">
            <a-select v-model:value="formState.state.contactsSex" placeholder="请选择">
              <a-select-option v-for="item in dictLists.data[dictEnum.SEX]"
                                :key="item.id" :value="item.value"
              >{{ item.label }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="状态" name="contactsState">
            <a-select v-model:value="formState.state.contactsState" placeholder="请选择">
              <a-select-option v-for="item in dictLists.data[dictEnum.CONTACT_STATUS]"
                                :key="item.id" :value="item.value"
              >{{ item.label }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="办公地址" name="contactsOfficeAddress">
            <a-input v-model:value="formState.state.contactsOfficeAddress" placeholder="请输入" maxlength="100" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <BasicTableModal v-model:visible="modalConfig.show"
      v-if="modalConfig.show"
      :columns="modalConfig.commonColumns"
      :fetchAjax="modalConfig.api"
      :title="modalConfig.title"
      :isinput="modalConfig.title==='选择学校'?true:false"
      @selectUniversity="value => selectItem(value, modalConfig.currentType)" />
  </a-modal>
</template>
<script setup>
import { save, selectById, update } from "@/api/module/contact-manage";
import {onMounted, reactive, ref, watch, toRaw, defineEmits, defineExpose, defineProps} from "vue";
import {useRoute, useRouter} from 'vue-router'
import { getDictByCodesReturnObj } from '@/tools/get-dict'
import dictEnum from '@/const/dict'
import { page as schoolPage } from '@/api/module/school'
import { page as userPage } from '@/api/module/user'
import BasicTableModal from '@/component/basic-table-modal'
import {message} from "ant-design-vue";
import { 
  emailPattern, // 邮箱
  phoneCardPattern, // 电话号码
} from "@/utils/validator.js"
const emit = defineEmits(['close'])
const props = defineProps({
  parent: Object
})
let isLoading = ref(false)
const formRef = ref();
const route = useRoute()
const router = useRouter()
const formState = reactive({
  state: {
    contactsName: '',
    contactsDepartment: '',
    contactsPosition: '',
    schId: '',
    schName: '',
    responsiblePerson: '',
    responsiblePersonId: '',
    contactsPhone: '',
    contactsEmail: '',
    contactsSex: null,
    contactsState: null,
    contactsOfficeAddress: '',
  }
});
const saveKey = "save";
const labelCol = { span: 6 }
const wrapperCol = { span: 18 }
watch(() => props.parent,
(value) => {
  if (value) {
    formState.state.schId = value.id
    formState.state.schName = value.schoolEnName
  }
}, { immediate: true, deep: true })
let dictLists = reactive({
  data: {}
})
const modalConfig = reactive({
  title: '选择学校',
  api: schoolPage,
  show: false,
  currentType: '',
  commonColumns: [],
  universityColumns: [],
  responsibleColumns: [],
})
const formRules = {
  contactsName: [ { required: true, message: '请输入联系人姓名', trigger: 'blur'} ],
  contactsDepartment: [ { required: true, message: '请输入所属部门', trigger: 'blur'} ],
  contactsPhone: [{ required: false, validator: async (rules, value) => {
        if (!value) return Promise.resolve()
        if (!phoneCardPattern.test(value)) {
          return Promise.reject('请输入正确电话号码')
        } else {
          return Promise.resolve()
        }
      }, trigger: 'blur' }],
  contactsEmail: [{ required: false, validator: async (rules, value) => {
        if (!value) return Promise.resolve()
        if (!emailPattern.test(value)) {
          return Promise.reject('请输入正确的邮箱地址')
        } else {
          return Promise.resolve()
        }
      }, trigger: 'blur' }],
};

const submit = (e) => {
  formRef.value
    .validate()
      .then(() => {
        console.log('formState.state: ', formState.state);
        save(toRaw(formState.state)).then((response)=>{
          if(response.success){
            message.success({ content: '保存成功', duration: 1 }).then(()=>{
              cancel();
            });
          }else{
            message.warning({ content: '保存失败', duration: 1 }).then(()=>{
              cancel();
            });
          }
        });
      })
      .catch(error => {
        console.log('error', error);
    });
};
const cancel = (e) => {
  formRef.value.resetFields();
  emit("close", false);
};

onMounted(async () => {
  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.FOLLOW_PROGRESS,
    dictEnum.CONTACT_STATUS,
    dictEnum.SEX,
  ])

  modalConfig.universityColumns = [
    { dataIndex: "code", key: "code", title: "学校编码" },
    { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校名称", },
    {
      dataIndex: "schFollowUpProgress",
      key: "schFollowUpProgress",
      title: "跟进进度",
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
          const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(v => v.value == data)
          return item ? item.label : ''
        }
        return ''
      }
    },
  ]

  modalConfig.responsibleColumns = [
    { dataIndex: "nickname", key: "nickname", title: "用户名称" },
    { dataIndex: "deptName", key: "deptName", title: "所属部门" },
    { dataIndex: "postName", key: "postName", title: "职位" },
  ]
})


const openDialog = (type) => {
  modalConfig.currentType = type
  modalConfig.commonColumns = type === 'schName' ? modalConfig.universityColumns : modalConfig.responsibleColumns
  modalConfig.api = type === 'schName' ? schoolPage : userPage
  modalConfig.title = type === 'schName' ? '选择学校' : '选择负责人'
  modalConfig.show = true
}


const selectItem = (value, type) => {
  formState.state.responsiblePerson = value.nickname
  formState.state.responsiblePersonId = value.id
}
</script>
<style lang="">

</style>
